/*
 * @Author: “ygnnli” “1585923072@qq.com”
 * @Date: 2024-08-01 23:46:38
 * @LastEditors: “ygnnli” “1585923072@qq.com”
 * @LastEditTime: 2024-08-02 10:46:24
 * @FilePath: /110/40/cp_ringqueue/RingQueue.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <semaphore.h>

template <typename T>
class RingQueue
{
private:
    void P(sem_t &sem)
    {
        sem_wait(&sem);
    }

    void V(sem_t &sem)
    {
        sem_post(&sem);
    }
    void Lock(pthread_mutex_t &mutex)
    {
        pthread_mutex_lock(&mutex);
    }

    void UnLock(pthread_mutex_t &mutex)
    {
        pthread_mutex_unlock(&mutex);
    }

public:
    RingQueue(int cap) : _cap(cap), _ring_queue(cap), _productor_step(0), _consumer_step(0)
    {
        sem_init(&_room_sem, 0, _cap);
        sem_init(&_data_sem, 0, 0);
        pthread_mutex_init(&_productor_mutex, nullptr);
        pthread_mutex_init(&_consumer_mutex, nullptr);
    }
    ~RingQueue()
    {
        sem_destroy(&_room_sem);
        sem_destroy(&_data_sem);

        pthread_mutex_destroy(&_productor_mutex);
        pthread_mutex_destroy(&_consumer_mutex);
    }

    void Enqueue(const T &in)
    {

        P(_room_sem);
        Lock(_productor_mutex); // 生产者加锁
        _ring_queue[_productor_step++] = in;
        _productor_step %= _cap;
        UnLock(_productor_mutex); // 生产者解锁
        V(_data_sem);
    }
    void Pop(T *out)
    {

        P(_data_sem);
        Lock(_consumer_mutex); // 消费者加锁
        *out = _ring_queue[_consumer_step++];
        _consumer_step %= _cap;
        UnLock(_consumer_mutex); // 消费者解锁
        V(_room_sem);
    }

private:
    std::vector<T> _ring_queue;
    int _cap;

    int _productor_step; // 生产
    int _consumer_step;  // 消费

    sem_t _room_sem; // 生产者关心
    sem_t _data_sem; // 消费者关心

    pthread_mutex_t _productor_mutex;
    pthread_mutex_t _consumer_mutex;
};